<template>
	<view class="post">
		<view class="post-item" v-for="(item,index) in list" :key="item.id" @click="onDetail(item,false)">

			<view class="level">
				<view class="level-left" @click.stop="toHomePage(item, index)">
					<u-avatar class="avatar" mode="aspectFill" :class="item.avatar?'':'avatar-b'" :src="item.avatar"
						size="35"></u-avatar>
					<view class="level-left-name">
						<view class="name">{{item.nickName}}</view>
						<view class="date" v-if="current!=0">{{item.createTime}}</view>
					</view>
				</view>
			</view>

			<view class="post-item-title">
				{{item.title?item.title:'暂无标题'}}
			</view>

			<post-shrink :text="item.content" :line="3" />

			<view class="album" @click.stop>
				<!-- 第一个资源是视频 -->
				<!-- #ifdef APP-PLUS || H5 -->
				<view :class="'video-container-' + item.id"
					v-if="item.files && item.files.length!=0 && item.files[0].isImage==0">
					<DomVideoPlayer :class="'video-'+index" :ref="'allPostRef'+item.id"
						@click.native.stop="openCustomFullScreenVideo(item.id, item.files[0].fileUrl)"
						@videoDidExitFullScreen="$emit('videoDidExitFullScreen')" :src="item.files[0].fileUrl" loop
						:muted="true" :autoplay="false" :isLoading="true"
						style="max-width: 600rpx;width:400rpx;max-height: 600rpx;" />
				</view>
				<!-- #endif -->
				<!--  -->
				<view v-if="item.files.length === 4 && item.files[0].isImage === 1" class="grid-tianzi">
					<view v-for="(file, fileIndex) in item.files" :key="fileIndex" class="grid-tianzi-item"
						@click.stop="previewImage(item.files, fileIndex)">
						<image style="width: 117px;height: 117px;"
							:src="file.previewImgUrl?file.previewImgUrl:file.fileUrl" :lazy-load="true"
							mode="aspectFill"></image>
						<!-- <u-image 
							:src="file.previewImgUrl?file.previewImgUrl:file.fileUrl" 
							width="117" 
							height="117"
							mode="aspectFill"
						></u-image> -->
					</view>
				</view>

				<custom-album v-else-if="item.files && item.files.length!=0 && item.files[0].isImage==1"
					:urls="item.files" image-url-key="fileUrlCached"
					@click.native.stop="previewFromCustomAlbum(item.files)"></custom-album>

				<view class="post-dw">
					<u-icon name="map" color="#666" size="22"></u-icon>
					<view class="single-line">
						{{getLocation(item.location)}}
					</view>
				</view>
			</view>

			<common-post-actions :data="item" @onDetail="onDetail(item, true)"></common-post-actions>
		</view>
		<!-- #ifdef APP-PLUS || H5 -->
		<VideoFullscreenModal :visible="showVideoModal" :video-src="currentModalVideoSrc"
			@close="closeCustomFullScreenVideo" />
		<!-- #endif -->

	</view>
</template>

<script>
	import PostShrink from "@/components/post-shrink/post-shrink.vue";
	import CComment from "@/components/XJ-comment/index.vue";
	// #ifdef APP-PLUS || H5
	import DomVideoPlayer from '@/components/DomVideoPlayer/DomVideoPlayer.vue';
	import VideoFullscreenModal from '@/components/VideoFullscreenModal/VideoFullscreenModal.vue';
	// #endif
	import {
		getClientFollow,
		postClientLike,
		postCancelLike,
		postClientCollect,
		postCancelCollect
	} from '@/request/api.js';
	import CustomAlbum from '@/components/custom-album/custom-album.vue';
	import commonPostActions from '@/components/common-post-actions/common-post-actions.vue'; // 引入组件

	export default {
		name: "common-post-localExperts",
		props: {
			list: {
				type: Array,
				default: () => []
			},
			current: {
				type: Number,
				default: null
			}
		},
		components: {
			PostShrink,
			CComment,
			CustomAlbum,
			commonPostActions,
			// #ifdef APP-PLUS || H5
			DomVideoPlayer,
			VideoFullscreenModal
			// #endif
		},
		data() {
			return {
				windowHeight: 0,
				defaultLoadingIcon: '/static/loading.gif',
				defaultErrorIcon: '/static/error.png',
				observers: {}, // 存储 IntersectionObserver 实例, key 为 item.id
				videoPlayers: {}, // 存储 video player refs, key 为 item.id
				showVideoModal: false,
				currentModalVideoSrc: '',
				currentModalVideoId: null,
			}
		},
		watch: {
			list: {
				handler(newList, oldList) {
					// 列表数据变化时，清理旧的观察器并为新项或变化的项设置观察器
					this.$nextTick(() => {
						this.cleanupAllObservers(); // 清理所有旧的
						this.initializeVideoObservers(); // 为当前列表重新初始化
					});
				},
				deep: true,
				immediate: true // 首次加载 list 时也执行
			}
		},
		mounted() {
			const systemInfo = uni.getSystemInfoSync();
			this.windowHeight = systemInfo.windowHeight;
		},
		beforeDestroy() {
			this.cleanupAllObservers();
		},
		methods: {
			getLocation(str) {
				const index = str.indexOf('-');
				return index !== -1 ? str.substring(index + 1) : '';
			},
			previewImage(originalFiles, currentIndex) {
				const urls = originalFiles.map(file => file.fileUrl);
				uni.previewImage({
					urls: urls,
					current: currentIndex,
					fail: (err) => {}
				});
			},
			previewFromCustomAlbum(originalFiles) {
				if (originalFiles && originalFiles.length > 0) {}
			},

			initializeVideoObservers() {
				if (!this.list || this.list.length === 0) return;

				this.list.forEach((item) => {
					if (item.files && item.files.length > 0 && item.files[0].isImage === 0) {
						const videoContainerClass = `.video-container-${item.id}`;
						const videoPlayerRefName = `allPostRef${item.id}`;

						this.$nextTick(() => { // 确保DOM已渲染
							const videoPlayerArray = this.$refs[videoPlayerRefName];
							if (videoPlayerArray && videoPlayerArray.length > 0 && videoPlayerArray[0]) {
								this.videoPlayers[item.id] = videoPlayerArray[0];

								if (this.observers[item.id]) { // 如果已存在，先断开
									this.observers[item.id].disconnect();
								}

								const observer = uni.createIntersectionObserver(this, {
									thresholds: [0.5], // 50% 可见时触发
									initialRatio: 0
								});

								observer.relativeToViewport({
										top: '0px',
										bottom: '0px'
									}) // 可根据页面实际情况调整
									.observe(videoContainerClass, (res) => {
										const player = this.videoPlayers[item.id];
										console.log("res.intersectionRatio", res);
										if (player) {
											if (res && res.intersectionRatio && res
												.intersectionRatio >= 0.5) {
												player.play();
												// this.$emit('videoPlaying', item.id); // 可选：通知父组件哪个视频在播放
											} else {
												player.pause();
											}
										}
									});
								this.observers[item.id] = observer;
							} else {
								console.warn(
									`Video player ref ${videoPlayerRefName} not found for item ${item.id}`
								);
							}
						});
					}
				});
			},

			cleanupObserverForItem(itemId) {
				if (this.observers[itemId]) {
					this.observers[itemId].disconnect();
					delete this.observers[itemId];
				}
				if (this.videoPlayers[itemId]) {
					if (typeof this.videoPlayers[itemId].pause === 'function') {
						this.videoPlayers[itemId].pause();
					}
					delete this.videoPlayers[itemId];
				}
			},

			cleanupAllObservers() {
				Object.keys(this.observers).forEach(itemId => {
					this.observers[itemId].disconnect();
				});
				this.observers = {};

				Object.values(this.videoPlayers).forEach(player => {
					if (player && typeof player.pause === 'function') {
						player.pause();
					}
				});
				this.videoPlayers = {};
			},
			// 播放指定视频 (如果父组件需要手动控制)
			playVideoById(itemId) {
				const player = this.videoPlayers[itemId];
				if (player && typeof player.play === 'function') {
					player.play();
				}
			},

			// 暂停指定视频
			pauseVideoById(itemId) {
				const player = this.videoPlayers[itemId];
				if (player && typeof player.pause === 'function') {
					player.pause();
				}
			},

			// 暂停所有视频
			pauseAllVideos() {
				Object.values(this.videoPlayers).forEach(player => {
					if (player && typeof player.pause === 'function') {
						player.pause();
					}
				});
			},
			fullScreenVideo(itemId) { // 参数改为 itemId
				const player = this.videoPlayers[itemId];
				if (player && typeof player.fullScreen === 'function') {
					// 在进入全屏前，通知父组件 (index.vue)，父组件可以暂停所有 IntersectionObserver
					this.$emit('beforeVideoEnterFullScreen');
					player.fullScreen();
					setTimeout(() => {
						if (player && typeof player.play === 'function') {
							player.play();
						}
					}, 100);
					// 注意：全屏事件的监听和退出全屏后的处理需要在父组件 (index.vue) 中实现
				}
			},
			openCustomFullScreenVideo(itemId, videoUrl) {
				// 1. Pause the inline video player
				this.pauseVideoById(itemId);

				// 2. Set data for the modal
				this.currentModalVideoSrc = videoUrl;
				console.log("this.currentModalVideoSrc", this.currentModalVideoSrc);
				this.currentModalVideoId = itemId; // Store for potential resume later
				this.showVideoModal = true;

				// 3. (Optional) If you had specific logic in 'beforeVideoEnterFullScreen', replicate or adapt it.
				// For example, if it was pausing IntersectionObservers, you might still want that.
				// this.$emit('beforeVideoEnterFullScreen'); 
			},
			closeCustomFullScreenVideo() {
				this.showVideoModal = false;
				this.currentModalVideoSrc = '';

				// Optional: Resume the inline player if it was the one opened.
				// Be cautious with this, as users might not expect auto-resume.
				// if (this.currentModalVideoId) {
				// 	const player = this.videoPlayers[this.currentModalVideoId];
				// 	if (player && player.isPaused()) { // Assuming DomVideoPlayer has an isPaused() method or similar state
				// 		 // player.play(); // Or, better, let IntersectionObserver handle resume when it's back in view
				// 	}
				// }
				this.currentModalVideoId = null;

				// (Optional) If you had specific logic for 'videoDidExitFullScreen' from the parent,
				// you might want to emit something similar here or call a method.
				// this.$emit('videoDidExitFullScreen'); // If parent component needs to know
			},
			setFollow(userId, newFollowStatus) {
				this.list.forEach((post, i) => {
					if (post.userId === userId) {
						this.$set(this.list[i], 'isFollowed', newFollowStatus ? 1 : 0);
					}
				});
			},
			onFollow(item, indexInList) {
				let currentFollowStatus = this.list[indexInList].isFollowed;
				let targetFollowStatus = currentFollowStatus === 0 ? 1 : 0;

				this.setFollow(item.userId, targetFollowStatus === 1);

				getClientFollow({
					userId: item.userId
				}).then(res => {
					if (res.data.code == 500) {
						this.setFollow(item.userId, currentFollowStatus === 1);
						uni.showToast({
							title: targetFollowStatus === 1 ? "关注失败" : "取消关注失败",
							icon: 'none',
						})
					}
				}).catch(err => {
					this.setFollow(item.userId, currentFollowStatus === 1);
					uni.showToast({
						title: '网络错误，请稍后重试',
						icon: 'none',
					})
				});
			},
			toHomePage(item) {
				let initialData = {
					userId: item.userId,
					isFollowed: item.isFollowed === 1 ? true : false
				}
				uni.navigateTo({
					url: '/pages_sub/user/others/others',
					events: {
						returnData: (returnedData) => {
							if (returnedData.userId === item.userId && typeof returnedData.isFollowed !==
								'undefined') {
								this.setFollow(returnedData.userId, returnedData.isFollowed);
							}
						}
					},
					success: (res) => {
						res.eventChannel.emit('sendInitData', {
							data: JSON.stringify(initialData)
						});
					}
				});
			},
			onDetail(item, scroll) {
				this.$emit('detailClick', {
					item,
					scroll: scroll || false
				});
			},
		}
	}
</script>

<style lang="scss">
	::v-deep .u-album__row__wrapper__text {
		background-color: rgba(0, 0, 0, 0.7);

	}

	::v-deep .u-text__value {
		font-size: 60rpx;
	}

	.video-container {
		width: auto;
		height: auto;
	}

	.video {
		object-fit: cover;
		position: relative;
		will-change: transform;
		transform: translateZ(0);
	}

	.post {
		background-color: #F8F8F8;

		// min-height: 600rpx;
		.post-item {
			background-color: #FFFFFF;
			position: relative;
			padding: 10rpx 40rpx 0 40rpx;
			// margin: 0 30rpx 30rpx 30rpx;
			// border-radius: 30rpx;
			margin-bottom: 20rpx;
			overflow: hidden;

			// box-shadow: 0 0 30rpx rgba(0, 0, 0, 0.05);
			.post-item-title {
				font-size: 36rpx;
				font-weight: bold;
				margin: 20rpx 0 10rpx;

				// 实现最多显示两行，超出显示省略号
				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-line-clamp: 2;
				overflow: hidden;
				text-overflow: ellipsis;
				line-height: 1.5; // 设置行高，可根据需要调整
			}
		}

		.avatar {
			width: 100rpx;
			height: 100rpx;
			border-radius: 50%;
		}

		.level-left-name {
			margin-left: 20rpx;
		}

		.avatar-b {
			border: 1rpx solid #FFAE1A;
		}

		.album {
			width: 100%;
			display: inline-block;
			margin-top: 15rpx;
			position: relative;
			z-index: 1;
			padding-bottom: 40rpx;
			border-bottom: 1rpx solid #F4F4F4;

			.grid-tianzi {
				display: grid;
				width: 424rpx;
				grid-template-columns: repeat(2, 1fr);
				grid-auto-rows: 1fr;
				gap: 4px;

				.grid-tianzi-item {
					width: 212rpx;
					aspect-ratio: 1 / 1;
					overflow: hidden;
				}
			}
		}

		.level {
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-bottom: 15rpx;
			padding: 15rpx 0;

			.level-left {
				display: flex;
				align-items: center;
				z-index: 9;
			}

			.level-right {
				display: flex;
				color: #FE4E4E;
				border: 1rpx solid #FE4E4E;
				border-radius: 50rpx;
				font-size: 26rpx;
				padding: 5rpx 15rpx;

				.icon {
					margin-right: 5rpx;
				}
			}

			.active {
				color: #cccccc;
				border: 1rpx solid #cccccc;
			}
		}

		.name {
			font-size: 32rpx;
		}

		.date {
			color: #787878;
			font-size: 22rpx;
			margin-top: 5rpx;
		}

		.describe {}

		.label {
			font-size: 24rpx;
			color: #FFAE1A;
		}

		.image {
			justify-content: space-between;
		}
	}

	.post-dw {
		color: #494A53;
		min-width: 130rpx;
		margin-right: 20rpx;
		margin-top: 20rpx;
		display: flex;
		align-items: center;
		font-size: 28rpx;

		.single-line {
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
			max-width: 500rpx;
			/* 需要设置宽度 */
		}

		// .single-line:hover {
		//   overflow: visible;  /* 悬停时显示全部内容 */
		//   white-space: normal; /* 允许换行 */
		// }

		.icon-dw {
			width: 40rpx;
			margin-right: 10rpx;
		}
	}

	.post-actions {
		display: flex;
		color: #787878;
		justify-content: space-around;
		padding: 10rpx 0;
		font-size: 24rpx;
		margin-top: 15rpx;

		.post-actions-item {
			display: flex;
			align-items: center;

			&-text {
				min-width: 40rpx;
				text-align: center;
			}
		}

		.image {
			width: 48rpx;
			height: 48rpx;
			margin-right: 10rpx;
		}

		text {}
	}
</style>